/*
	Assignment 4a : Reader and Writer using semaphore
	Name : Rushikesh M.Fanse
	Roll No : 16
	Div : H
*/
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<unistd.h>
#include<pthread.h>
#include<semaphore.h>
using namespace std;
sem_t mutex,library;
int rc;
void*reader(void* t_id)
{
	int tid;
	tid=(long)t_id;
		printf("reader %d is trying to enter\n",tid);
		sem_wait(&mutex);
		rc=rc+1;
		if(rc==1)
		{
			sem_wait(&library);
			printf("reader %d locked the library\n",tid);
		}
		sem_post(&mutex);
		printf("readers are reading\n");
		sleep(2);
		sem_wait(&mutex);
		rc=rc-1;
		if(rc==0)
		{	
			sem_post(&library);
			printf("reader %d unlocks the library\n",tid);
		}
		printf("reader %d exits \n",tid);
		sem_post(&mutex);
}
void*writer(void*)
{
		
		printf("--------------------writer tries to enter\n");
		sem_wait(&library);
		printf("-------------------writer is locked library and writing the book\n");
		sleep(2);
		sem_post(&library);
		printf("--------------------writer left\n");

}
int main()
{
	int i;
	pthread_t t1[5],t2;
	sem_init(&mutex,0,1);
	sem_init(&library,0,1);
	for(i=0;i<5;i++)
		pthread_create(&t1[i],NULL,reader,(void *)(intptr_t)i);
	pthread_create(&t2,NULL,writer,NULL);
	for(i=0;i<5;i++)
		pthread_join(t1[i],NULL);
	pthread_join(t2,NULL);
	sem_destroy(&mutex);
	sem_destroy(&library);
	return 0;
}
/*
output:
rishi@rishi-PC:~$ ./a.out
reader 1 is trying to enter
reader 4 is trying to enter
--------------------writer tries to enter
reader 2 is trying to enter
reader 1 locked the library
reader 0 is trying to enter
readers are reading
readers are reading
readers are reading
readers are reading
reader 3 is trying to enter
readers are reading
reader 0 exits 
reader 2 exits 
reader 4 exits 
reader 3 exits 
reader 1 unlocks the library
reader 1 exits 
-------------------writer is locked library and writing the book
--------------------writer left

*/
